package cn.j2ee.chapter2.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 
 * 2016年11月12日上午10:53:52
 */
public class HandlerInterceptor1 extends HandlerInterceptorAdapter{
	//此处一般继承HandlerInterceptorAdapter适配器即可  
	private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("StopWatch-StartTime");
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
        System.out.println("===========HandlerInterceptor1 preHandle"); 
        long beginTime = System.currentTimeMillis();
        startTimeThreadLocal.set(beginTime);
        return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
        System.out.println("===========HandlerInterceptor1 postHandle");  
       super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
        System.out.println("===========HandlerInterceptor1 afterCompletion");  
        long endTime = System.currentTimeMillis();
        long beginTime = startTimeThreadLocal.get();
        long consumeTime = endTime - beginTime;//3、消耗的时间  
        System.out.println(String.format("%s consume %d millis", request.getRequestURI(), consumeTime));  
        if(consumeTime > 500) {//此处认为处理时间超过500毫秒的请求为慢请求  
            System.out.println(String.format("Fatal:%s consume %d millis", request.getRequestURI(), consumeTime));  
        }          
        super.afterCompletion(request, response, handler, ex);
	}
	
}
